import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import styles from './index.module.css';

interface FormValues {
    password: string;
}

const LockScreen: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm<FormValues>();
    const navigate = useNavigate();
    const { initialState, setInitialState } = useModel('@@initialState');

    // 验证规则
    const validationRules = [
        {
            required: true,
            message: '请填写密码',
        },
        {
            validator: async (_: any, value: string) => {
                if (!value) {
                    return Promise.reject(new Error('请填写密码'));
                }
                
                const voucher = sessionStorage.getItem('voucher');
                const userInfo = sessionStorage.getItem('userinfo');
                if (!voucher || voucher !== 'Login-credentials' || !userInfo) {
                    return Promise.reject(new Error('未检测到登录状态，请重新登录'));
                }
                
                // 只从全局状态获取密码
                const storedPassword = initialState?.lockScreenPassword;

                // 如果没有存储的密码，则不允许解锁
                if (!storedPassword) {
                    return Promise.reject(new Error('未找到密码信息，请重新登录'));
                }

                if (value.trim() !== storedPassword) {
                    return Promise.reject(new Error('密码错误请重新输入'));
                }

                return Promise.resolve();
            }
        }
    ];

    const handleUnlock = async () => {
        try {
            setLoading(true);
            await form.validateFields();
            // 设置解锁标记
            sessionStorage.setItem('isUnlocking', 'true');
            // 清除锁屏状态
            localStorage.removeItem('isLocked');
            // 获取目标路径
            const redirectPath = localStorage.getItem('attemptedPath') || '/index';
            const safeRedirectPath = redirectPath === '/lock' ? '/index' : redirectPath;
            localStorage.removeItem('attemptedPath');

            message.success('解锁成功', 1);

            // 更新全局状态
            setInitialState((preInitialState) => ({
                ...preInitialState,
                isLoggedIn: true,
            }));

            // 立即跳转
            navigate(safeRedirectPath, { replace: true });
            
            // 跳转后清理解锁标记
            setTimeout(() => {
                sessionStorage.removeItem('isUnlocking');
                setLoading(false);
            }, 500);

        } catch (error) {
            console.log('解锁失败:', error);
            sessionStorage.removeItem('isUnlocking');
            setLoading(false);
        }
    };

    // 输入框事件处理
    const handleInputFocus = () => {
        form.setFields([{ name: 'password', errors: [] }]);
    };

    const handleInputBlur = () => {
        const value = form.getFieldValue('password');
        if (value && value.trim() !== '') {
            form.validateFields(['password']);
        }
    };

    // 登录状态检查（移除错误的 isLocked 设置）
    useEffect(() => {
        const timer = setTimeout(() => {
            const voucher = sessionStorage.getItem('voucher');
            const userInfo = sessionStorage.getItem('userinfo');
            const lockScreenPassword = initialState?.lockScreenPassword;

            // 检查有效登录信息
            if (!voucher || voucher !== 'Login-credentials' || !userInfo || !lockScreenPassword) {
                message.warning('未检测到有效的登录信息，请重新登录');
                sessionStorage.clear();
                localStorage.removeItem('isLocked'); // 清除无效锁屏状态
                navigate('/user/login', { replace: true });
                return;
            }

            // 如果是解锁过程中，直接跳转
            if (sessionStorage.getItem('isUnlocking') === 'true') {
                const redirectPath = localStorage.getItem('attemptedPath') || '/index';
                const safeRedirectPath = redirectPath === '/lock' ? '/index' : redirectPath;
                navigate(safeRedirectPath, { replace: true });
                return;
            }

            // 自动聚焦输入框
            const inputTimer = setTimeout(() => {
                const input = document.querySelector('input[type="password"]') as HTMLInputElement;
                if (input) {
                    input.focus();
                }
            }, 100);

            return () => clearTimeout(inputTimer);
        }, 300);

        return () => clearTimeout(timer);
    }, [initialState, navigate]);

    return (
        <div className={styles['lock-screen-container']}>
            <div className={styles['lock-modal']}>
                <div className={styles['title-group']}>
                    <div className={styles['lock-status']}>当前是锁屏状态</div>
                    <div className={styles['welcome-text']}>欢迎回来</div>
                </div>

                <Form
                    form={form}
                    layout="vertical"
                    className={styles['lock-form']}
                    initialValues={{ password: '' }}
                >
                    <Form.Item
                        name="password"
                        rules={validationRules}
                        validateFirst
                    >
                        <Input.Password
                            placeholder="请输入密码"
                            size="large"
                            prefix={<LockOutlined />}
                            onFocus={handleInputFocus}
                            onBlur={handleInputBlur}
                            onPressEnter={handleUnlock}
                            style={{
                                height: '42px',
                                borderRadius: '6px',
                                fontSize: '14px'
                            }}
                            autoComplete="new-password"
                        />
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            onClick={handleUnlock}
                            loading={loading}
                            block
                            style={{
                                height: '42px',
                                fontSize: '16px',
                                fontWeight: 500
                            }}
                        >
                            {loading ? '解锁中...' : '解锁进入系统'}
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default LockScreen;